/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    /// <summary>
    /// 
    /// </summary>
    public partial class PageExceptionModifiersImp : PageImpBaseClass
    {
        ListView listviewChosenMods;
        ListView listviewAvailableMods;
        ComboBox comboBoxGroupsName;
        ComboBox comboBoxExistingForcedMods;

        DbLinkedTextBox textBoxForceModGroupName;
        DbLinkedTextBox tbForcedGroupMenuLocWeight;
        DbLinkedTextBox textBoxGroupPrice;
        DbLinkedTextBox tbForcedModName;
        DbLinkedTextBox tbSku;
        DbLinkedTextBox tbPlu;
        DbLinkedTextBox tbForcedModPrice;
        DbLinkedTextBox tbRevenueType;
        DbLinkedTextBox tbSurchargeType;
        DbLinkedTextBox tbExclusiveTax;
        DbLinkedTextBox tbInclusiveTax;
        DbLinkedTextBox tbForceModMenuWeight;

        Button buttonAddSelectedMods;
        Button buttonRemoveSelectedMods;


        /// Constructor
        /// </summary>
        public PageExceptionModifiersImp(
            ListView listviewChosenMods,
            ListView listviewAvailableMods,
            UIElementCollection uielementsChildren,
            ComboBox comboBoxGroupsName,
            ComboBox comboBoxExistingForcedMods,
            DbLinkedTextBox textBoxGroupName,
            DbLinkedTextBox tbForcedGroupMenuLocWeight,
            DbLinkedTextBox textBoxGroupPrice,
            DbLinkedTextBox tbForcedModName,
            DbLinkedTextBox tbSku,
            DbLinkedTextBox tbPlu,
            DbLinkedTextBox tbUpc,
            DbLinkedTextBox tbInclusiveTip,
            DbLinkedTextBox tbForcedModPrice,
            DbLinkedTextBox tbRevenueType,
            DbLinkedTextBox tbSurchargeType,
            DbLinkedTextBox tbExclusiveTax,
            DbLinkedTextBox tbInclusiveTax,
            DbLinkedTextBox tbForceModMenuWeight,
            Button buttonAddSelectedMods,
            Button buttonRemoveSelectedMods,
            Button bRevenueType,
            Button bSurcharge,
            Button bExclTax,
            Button bAssignInclusiveTax,
            Button bAssignInclusiveTip,
            GroupBox fmEntityGroupBox,
            GroupBox fmGroupsGroupBox)
            : base()
        {
            this.ButtonNumber = "8";
            this.ButtonLabelText = "Exception Modifiers";
            mButtonDeleteEntityName = "Delete Modifier";
            mButtonNewEntityName = "New Modifier";
            mButtonNewGroupName = "New Modifier Group";
            mButtonDeleteGroupName = "Delete Modifier Group";

            RegisterSaveMeGroupBoxes(fmGroupsGroupBox, fmEntityGroupBox);

            this.listviewAvailableMods = listviewAvailableMods;
            this.listviewChosenMods = listviewChosenMods;

            this.comboBoxGroupsName = comboBoxGroupsName;
            this.comboBoxExistingForcedMods = comboBoxExistingForcedMods;
            this.textBoxForceModGroupName = textBoxGroupName;
            this.tbForcedGroupMenuLocWeight = tbForcedGroupMenuLocWeight;
            this.textBoxGroupPrice = textBoxGroupPrice;
            this.tbForcedModName = tbForcedModName;
            this.tbSku = tbSku;
            this.tbPlu = tbPlu;
            this.tbForcedModPrice = tbForcedModPrice;
            this.tbRevenueType = tbRevenueType;
            this.tbSurchargeType = tbSurchargeType;
            this.tbExclusiveTax = tbExclusiveTax;
            this.tbInclusiveTax = tbInclusiveTax;
            this.tbForceModMenuWeight = tbForceModMenuWeight;

            this.buttonAddSelectedMods = buttonAddSelectedMods;
            this.buttonRemoveSelectedMods = buttonRemoveSelectedMods;

            mTextBoxesList.Add(textBoxGroupName);
            mTextBoxesList.Add(tbForcedGroupMenuLocWeight);
            mTextBoxesList.Add(textBoxGroupPrice);
            mTextBoxesList.Add(tbForcedModName);
            mTextBoxesList.Add(tbSku);
            mTextBoxesList.Add(tbPlu);
            mTextBoxesList.Add(tbUpc);
            mTextBoxesList.Add(tbInclusiveTip);
            mTextBoxesList.Add(tbForcedModPrice);
            mTextBoxesList.Add(tbRevenueType);
            mTextBoxesList.Add(tbSurchargeType);
            mTextBoxesList.Add(tbExclusiveTax);
            mTextBoxesList.Add(tbInclusiveTax);
            mTextBoxesList.Add(tbForceModMenuWeight);


            RegisterListview(listviewAvailableMods);
            RegisterListview(listviewChosenMods);
            RegisterUiElementsList(uielementsChildren);

            ListofComboboxes.Add(comboBoxGroupsName);
            ListofComboboxes.Add(comboBoxExistingForcedMods);

            listviewAvailableMods.SelectionChanged += new SelectionChangedEventHandler(listviewModifiers_SelectionChanged_NOTHROW);
            listviewChosenMods.SelectionChanged += new SelectionChangedEventHandler(listviewModifiers_SelectionChanged_NOTHROW);


            mListOfControlsToHideInNonEditMode.Add(buttonAddSelectedMods);
            mListOfControlsToHideInNonEditMode.Add(buttonRemoveSelectedMods);

            mListOfControlsToHideInNonEditMode.Add(bRevenueType);
            mListOfControlsToHideInNonEditMode.Add(bSurcharge);
            mListOfControlsToHideInNonEditMode.Add(bExclTax);
            mListOfControlsToHideInNonEditMode.Add(bAssignInclusiveTax);
            mListOfControlsToHideInNonEditMode.Add(bAssignInclusiveTip);

            buttonAddSelectedMods.Click += new RoutedEventHandler(buttonAddSelectedMods_Click);
            buttonRemoveSelectedMods.Click += new RoutedEventHandler(buttonRemSelectedMods_Click);
            bRevenueType.Click += new RoutedEventHandler(bRevenueType_Click);
            bSurcharge.Click += new RoutedEventHandler(bSurcharge_Click);
            bExclTax.Click += new RoutedEventHandler(bExclTax_Click);
            bAssignInclusiveTax.Click += new RoutedEventHandler(bAssignInclusiveTax_Click);
            bAssignInclusiveTip.Click += new RoutedEventHandler(bAssignInclusiveTip_Click);
            ///If the selection changes lock the form down.
            comboBoxGroupsName.SelectionChanged += new SelectionChangedEventHandler(comboBoxGroupsName_SelectionChanged);


            mEntityAddDeleteLoggingEnabled = true;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void bAssignInclusiveTip_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EXCEPTION_MODIFIER fm = comboBoxExistingForcedMods.SelectedItem as EXCEPTION_MODIFIER;
                if (fm != null)
                {
                    InclusiveTipSelectionListBox sb = new InclusiveTipSelectionListBox(Context);
                    sb.SetMessage("Select an inclusive tip rate from the list, or create a new inclusive tip rate.  Inclusive tip rates are built-in to the price of the product itself and are a form of auto-gratuity.  Some bars and night clubs prefer to price their servers tips into the product cost and use this method to help pay their employees' wages.");
                    sb.InitChoices();
                    sb.ShowDialog();
                    if (InclusiveTipSelectionListBox.LastResponse == UserResponse.ENTER)
                    {
                        fm.InclusiveTipRateId = InclusiveTipSelectionListBox.ChosenId;
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void bAssignInclusiveTax_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EXCEPTION_MODIFIER fm = comboBoxExistingForcedMods.SelectedItem as EXCEPTION_MODIFIER;
                if (fm != null)
                {
                    InclusiveTaxSelectionListBox sb = new InclusiveTaxSelectionListBox(Context);
                    sb.InitChoices();
                    sb.ShowDialog();
                    if (InclusiveTaxSelectionListBox.LastResponse == UserResponse.ENTER)
                    {
                        fm.InclusiveTaxRateId = InclusiveTaxSelectionListBox.ChosenId;
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void bExclTax_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EXCEPTION_MODIFIER fm = comboBoxExistingForcedMods.SelectedItem as EXCEPTION_MODIFIER;
                if (fm != null)
                {
                    ExclusiveTaxSelectionListBox sb = new ExclusiveTaxSelectionListBox(Context);
                    sb.SetMessage("Select an exclusive tax rate from the list or create a new exclusive tax rate.  Exclusive tax is the accounting term used to describe what most people think of as sales tax.");
                    sb.InitChoices();
                    sb.ShowDialog();
                    if (ExclusiveTaxSelectionListBox.LastResponse == UserResponse.ENTER)
                    {
                        fm.ExclusiveTaxRateId = ExclusiveTaxSelectionListBox.ChosenId;
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void bSurcharge_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EXCEPTION_MODIFIER fm = comboBoxExistingForcedMods.SelectedItem as EXCEPTION_MODIFIER;
                if (fm != null)
                {
                    SurchargeSelectionListBox sb = new SurchargeSelectionListBox(Context);
                    sb.SetMessage("Select a surcharge rate from the list or create a new surcharge rate.");
                    sb.InitChoices();
                    sb.ShowDialog();
                    if (SurchargeSelectionListBox.LastResponse == UserResponse.ENTER)
                    {
                        fm.SurchargeId = SurchargeSelectionListBox.ChosenId;
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void bRevenueType_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EXCEPTION_MODIFIER fm = comboBoxExistingForcedMods.SelectedItem as EXCEPTION_MODIFIER;
                if (fm != null)
                {
                    List<string> namesList = new List<string>();
                    List<Int64> idsList = new List<Int64>();

                    var q = from RT in Context.REVENUE_TYPES where RT.IsDeleted == false select RT;
                    if (q.Any())
                    {
                        List<REVENUE_TYPE> revTypes = q.ToList();
                        foreach (REVENUE_TYPE rt in revTypes)
                        {
                            namesList.Add(rt.Name);
                            idsList.Add(rt.Id);
                        }
                    }
                    RevenueTypeSelectionListBox sb = new RevenueTypeSelectionListBox(namesList, idsList, Context);
                    sb.SetMessage("Select a revenue type from the list, or create a new type.  An example of a revenue type is Alcohol, Dairy or Meat.");
                    sb.ShowDialog();
                    if (RevenueTypeSelectionListBox.LastResponse == UserResponse.ENTER)
                    {
                        fm.RevenueTypeId = RevenueTypeSelectionListBox.ChosenId;
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        override public List<EntityObject> GetGroupObjectSet()
        {
            try
            {
                var q = from FMG in Context.EXCEPTION_MODIFIER_GROUPS where FMG.IsDeleted == false select FMG;
                if (q.Any())
                {
                    return new List<EntityObject>(q.ToList());
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        override public List<EntityObject> GetEntityObjectSet()
        {
            try
            {
                var q = from FM in Context.EXCEPTION_MODIFIERS where FM.IsDeleted == false select FM;
                if (q.Any())
                {
                    return new List<EntityObject>(q.ToList());
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void comboBoxGroupsName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateListViews();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void listviewModifiers_SelectionChanged_NOTHROW(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (this.IsEditableMode())
                {
                    ListView lv = sender as ListView;
                    if (lv == listviewAvailableMods)
                    {
                        if (lv.SelectedItems.Count != 0)
                        {
                            buttonAddSelectedMods.IsEnabled = true;
                        }
                        else
                        {
                            buttonAddSelectedMods.IsEnabled = false;
                        }
                    }
                    else if (lv == listviewChosenMods)
                    {
                        if (lv.SelectedItems.Count != 0)
                        {
                            buttonRemoveSelectedMods.IsEnabled = true;
                        }
                        else
                        {
                            buttonRemoveSelectedMods.IsEnabled = false;
                        }
                    }
                }
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PAGEFORMODGR_LISTVIEW_SELECTION_CHANGE, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public override void ResetFocus()
        {
            base.ResetFocus();
            buttonRemoveSelectedMods.IsEnabled = false;
            buttonAddSelectedMods.IsEnabled = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAddSelectedMods_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EXCEPTION_MODIFIER_GROUP modGroup = comboBoxGroupsName.SelectedItem as EXCEPTION_MODIFIER_GROUP;
                if (modGroup != null)
                {
                    foreach (object prodMod in listviewAvailableMods.SelectedItems)
                    {
                        modGroup.EXCEPTION_MODIFIERS.Add(prodMod as EXCEPTION_MODIFIER);
                    }
                    UpdateListViews();
                }
            }
            catch { }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonRemSelectedMods_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EXCEPTION_MODIFIER_GROUP modGroup = comboBoxGroupsName.SelectedItem as EXCEPTION_MODIFIER_GROUP;
                if (modGroup != null)
                {
                    foreach (object prodMod in listviewChosenMods.SelectedItems)
                    {
                        modGroup.EXCEPTION_MODIFIERS.Remove(prodMod as EXCEPTION_MODIFIER);
                    }
                }
                UpdateListViews();
            }
            catch { }
        }

        /// <summary>
        /// 
        /// </summary>
        private void UpdateListViews()
        {
            EXCEPTION_MODIFIER_GROUP forcedModgroup = comboBoxGroupsName.SelectedItem as EXCEPTION_MODIFIER_GROUP;
            if (forcedModgroup != null)
            {
                List<EXCEPTION_MODIFIER> fmods = new List<EXCEPTION_MODIFIER>();
                var qAvailable = from FM in Context.EXCEPTION_MODIFIERS
                                 where FM.IsDeleted == false
                                 orderby FM.Name
                                 select FM;

                List<EXCEPTION_MODIFIER> usedList = null;
                if (qAvailable.Any())
                {
                    usedList = forcedModgroup.EXCEPTION_MODIFIERS.ToList();
                    foreach (EXCEPTION_MODIFIER fm in qAvailable)
                    {
                        if (!usedList.Contains(fm))
                        {
                            fmods.Add(fm);
                        }
                    }
                }

                listviewAvailableMods.ItemsSource = fmods;
                listviewChosenMods.ItemsSource = usedList;
            }
            else
            {
                listviewAvailableMods.ItemsSource = null;
                listviewChosenMods.ItemsSource = null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override EntityObject GetSelectedGroupObject()
        {
            EXCEPTION_MODIFIER_GROUP selected = comboBoxGroupsName.SelectedItem as EXCEPTION_MODIFIER_GROUP;
            return selected;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override EntityObject GetSelectedEntityObject()
        {
            EXCEPTION_MODIFIER selected = comboBoxExistingForcedMods.SelectedItem as EXCEPTION_MODIFIER;
            return selected;
        }

        /// <summary>
        /// 
        /// </summary>
        public override void MarkGroupDeleted()
        {
            EXCEPTION_MODIFIER_GROUP selected = comboBoxGroupsName.SelectedItem as EXCEPTION_MODIFIER_GROUP;
            if (selected != null)
            {
                selected.IsDeleted = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public override void MarkEntityDeleted()
        {
            EXCEPTION_MODIFIER selected = comboBoxExistingForcedMods.SelectedItem as EXCEPTION_MODIFIER;
            if (selected != null)
            {
                selected.IsDeleted = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        public override void UpdateUsersGroupSource()
        {
            try
            {
                ///Create the query object.
                var query = from EXCEPTION_MODIFIER_GROUP in
                                Context.EXCEPTION_MODIFIER_GROUPS
                            where EXCEPTION_MODIFIER_GROUP.IsDeleted == false
                            orderby EXCEPTION_MODIFIER_GROUP.Name
                            select EXCEPTION_MODIFIER_GROUP;

                if (query.Any())
                {
                    List<EXCEPTION_MODIFIER_GROUP> list = query.ToList();
                    comboBoxGroupsName.ItemsSource = list;
                    if (list != null && list.Count != 0)
                    {
                        comboBoxGroupsName.SelectedItem = list.First();
                    }
                    else
                    {
                        comboBoxGroupsName.ItemsSource = null;
                    }
                }
                else
                {
                    comboBoxGroupsName.ItemsSource = null;
                }
                UpdateListViews();
            }
            catch { }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        public override void UpdateUsersEntitySource()
        {
            try
            {
                ///Create the query object.
                var query = from EXCEPTION_MODIFIER in
                                Context.EXCEPTION_MODIFIERS
                            where EXCEPTION_MODIFIER.IsDeleted == false
                            orderby EXCEPTION_MODIFIER.Name
                            select EXCEPTION_MODIFIER;

                if (query.Any())
                {
                    List<EXCEPTION_MODIFIER> list = query.ToList();
                    comboBoxExistingForcedMods.ItemsSource = list;
                    if (list != null && list.Count != 0)
                    {
                        comboBoxExistingForcedMods.SelectedItem = list.First();
                    }
                    else
                    {
                        comboBoxExistingForcedMods.ItemsSource = null;
                    }
                }
                else
                {
                    comboBoxExistingForcedMods.ItemsSource = null;
                }
            }
            catch { }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override EntityObject AddNewGroupObject()
        {
            EXCEPTION_MODIFIER_GROUP newObject = null;
            try
            {
                var q = from EXCEPTION_MODIFIER_GROUP in Context.EXCEPTION_MODIFIER_GROUPS
                        where EXCEPTION_MODIFIER_GROUP.Name.Equals("Not Assigned")
                        select EXCEPTION_MODIFIER_GROUP;

                if (q.Count() == 0)
                {
                    newObject = new EXCEPTION_MODIFIER_GROUP();
                    newObject.Name = "Not Assigned";
                    Context.EXCEPTION_MODIFIER_GROUPS.AddObject(newObject);
                }
                else
                {
                    newObject = q.First();
                    if (newObject.IsDeleted)
                    {
                        newObject.IsDeleted = false;
                    }
                }
            }
            catch { }
            return newObject;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override EntityObject AddNewEntityObject()
        {
            EXCEPTION_MODIFIER newObject = null;
            try
            {
                var q = from EXCEPTION_MODIFIER in Context.EXCEPTION_MODIFIERS
                        where EXCEPTION_MODIFIER.Name.Equals("Not Assigned")
                        select EXCEPTION_MODIFIER;

                if (q.Count() == 0)
                {
                    newObject = new EXCEPTION_MODIFIER();
                    newObject.Name = "Not Assigned";
                    Context.EXCEPTION_MODIFIERS.AddObject(newObject);
                }
                else
                {
                    newObject = q.First();
                    if (newObject.IsDeleted)
                    {
                        newObject.IsDeleted = false;
                    }
                }
            }
            catch { }
            return newObject;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override ComboBox GetGroupComboBox()
        {
            return comboBoxGroupsName;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override ComboBox GetEntityComboBox()
        {
            return comboBoxExistingForcedMods;
        }
    }
}
